package com.xyh.flowershop.strategy;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xyh.flowershop.constant.CacheConstant;
import com.xyh.flowershop.domain.User;
import com.xyh.flowershop.enums.LoginEnum;
import com.xyh.flowershop.exceptions.custom.BizException;
import com.xyh.flowershop.vo.req.user.LoginUser;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author 小约翰可汗
 * @className EmailLogin
 * @createTime 2024/7/1413:13
 */
@Component
public class EmailLogin extends AbstractLogin {




    @Override
    public String login(LoginUser loginUser) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, loginUser.getAccount());
        User one = userService.getOne(wrapper);
        Optional.ofNullable(one).orElseThrow(() -> new BizException("邮箱未被注册"));
        String verifyCode = redisCache.getCacheObject(CacheConstant.LOGIN_VERIFY_CODE_PREFIX + one.getId());
        Optional.ofNullable(verifyCode).orElseThrow(() -> new BizException("验证码已过期"));
        if(verifyCode.equals(loginUser.getLoginToken())){
            String token = creatToken(one.getId());
            redisCache.setCacheObject(CacheConstant.LOGIN_PREFIX + one.getId(), token);
            return token;
        }
        throw new BizException("验证码错误");
    }

    @Override
    protected Integer getType() {
        return LoginEnum.EMAIL_LOGIN.getCode();
    }
}
